<template>
	<div class="project">
		<div class="project-menu">
			<div class="scroll-bar">
				<div class="menu-container">
					<g-menu-item 
						class="menu-item"
						:data="appList"
						:selected="selected"
						:key="appList.name"
						@on-select="switchProjectType" ></g-menu-item>
				</div>
			</div>
			
		</div>
		
		<div class="project-content">
			<transition name="fade">
                <div class="content-loading" v-if="isSwitching">
                    <div class="conent-loading-animate">
                        <div></div><div></div><div></div>
                    </div>
                </div>
            </transition>
			<keep-alive>
				<router-view
					:isLoading="loading"
					:currentApp="currentApp"
					:projects="currentProjects"
					v-on:search="search"
					v-on:add-more="addMore"
					v-on:sort-time="reSort"
					v-on:switch-view="switchView"
					v-on:remove-project="remove"></router-view>
			</keep-alive>
		</div>
	</div>
</template>

<script>

	import Bus from '@/utils/event_bus'
	import GMenuItem from '@/components/common/g-menu-item'
	import GButton from '@/components/common/g-button'
	import ProjectList from './project-list'
	import { appNameMapping } from '@/config/config'
	import { appsInUse } from '@/config/config'
	import {project as projectApi} from '@/api'
	import {app as appApi} from '@/api'

	const limit = 60;
	let myApps = '';
	let projectsCount = '';

	export default{
		name: 'project',

		data (){
			return {
				apps: '',
				currentApp: {},
				currentProjects: [],
				loading: false,
				selected: '',
				remind: true,
				appList: {
					name: '我的项目',
					submenu: [
						
					]
				},
				projectsList: { },
				isMounted: false,
				isSwitching: false,
			}
		},

		components: {
			GMenuItem,
			GButton,
			ProjectList
		},

		async mounted () {

			this.getMyApps();
			await this.init();
			let path = this.$router.currentRoute.path;
			let paths = path.split('/');
			await this.switchProjectType(paths[2]);
			this.isMounted = true;
			
			this.$emit( 'on-view-load' );
			let name = this.getAppListByKey(paths[2]).name;
			Bus.$emit('on-submenu-change', name);

			//console.log(this.selected);
			
		},

		activated () {

			let selected = this.selected;

			if (selected) {
				if (selected === 'all') {
	            	this.$router.push( { path: selected } );
	            } else {
	            	this.$router.push( { name: 'AppProjects', params: {type: selected} } );
	            }
			}
	        
	        if (this.isMounted) {
				this.$emit( 'on-view-load' );
	        }
	    },

		methods: {

			getMyApps () {

				// 暂时不需要用户添加程序，默认全都可用
				// let result = await appApi.list();

				// if (!result || result.data.code != 0) {
				// 	this.$message.error('获取应用失败');
				// 	return;
				// }

				// myApps = result.data.data;
				

				myApps = appsInUse;

			},

			async getProjectsCount () {

				let result = await projectApi.count();

				if (!result || result.data.code != 0 ) {
					return false;
				}

				let counts = result.data.data;
				projectsCount = {};

				counts.forEach((n) => {
					projectsCount[n.type] = n.count;
				})

				return true;
			},

			async init () {

				let obj = {
					order: 'desc',
					page: 1,
					search: ''
				}

				let arr = [];
				let total = 0;

				let result = await this.getProjectsCount();

				if (!result) {
					this.$message.error('获取应用数量失败');
					return;
				}

				myApps.forEach((n) => {

					let app = appNameMapping[n.name];
					let count = projectsCount[n.name];
					count = (typeof count !== 'number') ? 0 : count;

					if (app && app.hasOwnProperty('projects')) {

						let item = Object.assign({}, app, obj);
						item.count = count || 0;
						item.hasNext = count > limit;
						total = total + Number(count);

						arr.push(item);
					}

				})

				arr.unshift({
					name: '所有项目',
					key: 'all',
					icon:'project2',
					rootPath:'',
					projects: true,
					order: 'desc',
					page: 1,
					search: '',
					view: 'tiling-wrapper',
					hasNext: !!(total > limit),
					count: total
				})

				this.$set(this.appList, 'submenu', arr);

			},

			hideRemind () {
				this.remind = false;
			},

			async switchProjectType (key) {

				if (key === this.selected) return;

				let app = this.getAppListByKey(key);
				
	            this.selected = key;
	            this.currentApp = app;

	            let projects = this.projectsList[key];

	            if (!projects || !projects.length) {
	            	this.isSwitching = true;
	            	projects = await this.getProjects();
	            }
	            
	            this.currentProjects = this.projectsList[key] = projects;

	            if (key === 'all') {
	            	this.$router.push( { path: key } );
	            } else {
	            	this.$router.push( { name: 'AppProjects', params: {type: key} } );
	            }

	            this.isSwitching = false;
			},

			getAppListByKey (key) {

				let apps = this.appList.submenu;

				let app = apps.filter((n) => {
					return n.key === key;
				})

				return app[0];
			},

			async search () {
				let app = this.currentApp;
				app.page = 1;

				let res = await this.getProjects();

				if (!res) {
					this.$message.error('搜索失败');
					return;
				};

				if (!res.length) {
					this.$message.warning('未查询到结果');
					return;
				}

				app.hasNext = !(res.length < limit);
				this.currentProjects = [].concat(res);
			},

			async addMore () {
				let app = this.currentApp;

				app.page += 1;

				let res = await this.getProjects();

				if (!res) {
					this.$message.error('加载失败');
					app.page = app.page - 1;
					return
				};
				
				app.hasNext = !(res.length < limit);

				this.currentProjects = this.currentProjects.concat(res);
			},

			async reSort () {

				let app = this.currentApp;

				app.order = (app.order === 'desc') ? 'asc' : 'desc';
				app.page = 1;

				let res = await this.getProjects();

				if (!res) {
					this.$message.error('排序失败');
					app.order = (app.order === 'desc') ? 'asc' : 'desc';
					return
				};

				app.hasNext = !(res.length < limit) 

				this.currentProjects = [].concat(res);

			},

			switchView (view) {
				this.currentApp.view = view;
			},

			async getProjects () {

				this.loading = true;

				let app = this.currentApp;

				let params = {
					type: app.key === 'all' ? '' : app.key,
					title: app.search,
					page: app.page,
					limit: limit,
					order: app.order
				}

				let result = await projectApi.list(params);

				this.loading = false;

				if (result.data.code !== 0) {
					return null;
				}

				let data = result.data.data;

				// app.hasNext = !(data.length < limit) 

				return data;
			},

			async remove (key, index) {

				let projectList = this.projectsList[key];
				let item = projectList[index];
				let uid = item.uid;
				let app = item.type;

				projectList.splice(index, 1);

				let submenu = this.appList.submenu;

				submenu.forEach((n) => {
					if (n.key === 'all' || n.key === app) {
						n.count -= 1;
					}	
				})

				projectList = (key === app) ? this.projectsList['all'] : this.projectsList[app];

				let len = projectList.length;
				let linkIndex = '';

				for (let i = 0; i < len; i++) {
					if (projectList[i]['uid'] === uid) {
						linkIndex = i;
						break;
					}
				}

				if (Number.isInteger(linkIndex)) {
					projectList.splice(linkIndex, 1);
				}

			}
		}
	}
</script>

<style lang="scss">
	
	@import 'common';

	.project {

		height: 100%;

		.project-menu{
			float:left;
			height: 100%;
			width: 180px;
			overflow: hidden;

			.scroll-bar {

				height: 100%;
				overflow-y: scroll;
				overflow-x: hidden;
				margin-right: -15px;
				position: relative;

				.menu-container {

					border-right: 1px solid #ccc;
					min-height: 100%;
					padding-bottom: 12px;
					width: 180px;

					.menu-item {
						margin-right: -1px;
					}

					.project-remind {
						font-size: 12px;
						margin: 12px 12px 0 12px;
						border: 1px solid #ccc;
						border-radius: 4px;
						padding: 8px;

						.confirm {
							text-align: center;margin-top: 12px;
						}
					}
				}
			}
			
		}

		.project-content{
			height: 100%;
			overflow: hidden;
			position: relative;
		}
	}

	
</style>